package com.etogc.groupchat.group.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.etogc.groupchat.R;
import com.etogc.groupchat.base.BaseActivity;
import com.etogc.groupchat.bean.UpdatePhotoBean;
import com.etogc.groupchat.group.biz.GroupHttpBiz2;
import com.etogc.http.ReqDataHandler;
import com.etogc.http.ReqErrorHandler;
import com.etogc.http.VolleyHttpUtil;
import com.etogc.util.BitmapUtil;
import com.etogc.util.GcUrl;
import com.etogc.util.ImageUtils;
import com.etogc.util.IntentHelper;
import com.etogc.util.SoftKeyboardUtil;
import com.etogc.util.YcToastHelper;
import com.etogc.util.photo.Bimp;
import com.etogc.util.photo.PhotoActivity;
import com.etogc.view.LoadDialog;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理群
 */
public class MgrGroupActivity extends BaseActivity implements View.OnClickListener {


    private String groupID;
    private boolean hasMember = false;
    private RecyclerView mRecycler;
    private TextView mTvGrouName;
    private TextView tvMemberNum;
    private TextView mTvGrouId;
    private TextView mGroupName;
    private ImageView mIvGrouId;
    private EditText mEtIntro;
    private List<HashMap<String, String>> memberList = new ArrayList<>();

    public Map<String, Object> mGroupInfo;
    private String photoPath = "";
    private MemberAdapter memberAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mgr_group);
        ((TextView) findViewById(R.id.tvTitle)).setText("群管理");
        groupID = getIntent().getStringExtra("groupID");

        findViewById(R.id.ivBack).setVisibility(View.VISIBLE);
        findViewById(R.id.ivBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentHelper.finish(MgrGroupActivity.this);
            }
        });

        mRecycler = findViewById(R.id.recycler_view);
        mTvGrouName = findViewById(R.id.tvName);
        tvMemberNum = findViewById(R.id.tvMemberNum);
        mTvGrouId = findViewById(R.id.tv_group_id);
        mGroupName = findViewById(R.id.ivRight5);
        mIvGrouId = findViewById(R.id.ivLogo);
        mEtIntro = findViewById(R.id.et_intro);
        findViewById(R.id.rl_logo).setOnClickListener(this);
        findViewById(R.id.rlMgrMember).setOnClickListener(this);

        memberAdapter = new MemberAdapter();
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecycler.setLayoutManager(llm);
        mRecycler.setAdapter(memberAdapter);

        requestInfo();
        requestMemberNum();

        SoftKeyboardUtil.setEnterActionComplete(mEtIntro, new SoftKeyboardUtil.OnSoftEnterClickListener() {
            @Override
            public void OnSoftEnterClick() {
                if (mGroupInfo != null) {
                    String remark = String.valueOf(mGroupInfo.get("is_master"));
                    if (remark.equals("0")) {
                        YcToastHelper.getInstance()._toast("只有群主可以修改简介");
                    } else {
                        String intro = mEtIntro.getText().toString().trim();
                        if (TextUtils.isEmpty(intro)) {
                            YcToastHelper.getInstance()._toast("请输入简介内容");
                        } else {
                            updateGroupInfo(intro);
                        }
                    }
                } else {
                    YcToastHelper.getInstance()._toast("请稍后再试");
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ivBack:
                IntentHelper.finish(MgrGroupActivity.this);
                break;

            case R.id.rlMgrMember:
                if (hasMember) {
                    jumpMgrMember();
                } else {
                    YcToastHelper.getInstance()._toast("暂无群成员");
                }
                break;

            case R.id.rl_logo:
                if (mGroupInfo != null) {
                    String remark = String.valueOf(mGroupInfo.get("is_master"));
                    if (remark.equals("0")) {
                        YcToastHelper.getInstance()._toast("只有群主可以修改头像");
                    } else {
                        Intent intent = new Intent(this, PhotoActivity.class);
                        startActivityForResult(intent, 5);
                    }
                } else {
                    YcToastHelper.getInstance()._toast("请稍后再试");
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /* 拍照返回的图片 */
        if (requestCode == 5 && resultCode == 99) {
            if (data != null) {
                photoPath = data.getStringExtra("photoPath");
                setHeadImageAfterUpload();
            }
        }
    }

    private String saveBitmap(Bitmap bitmap) {
        String path = Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".jpg";
        Log.e("MineFragment", "path=" + path);
        File file = new File(path);
//        File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 上传头像后，不去网络下载，而是直接使用本地地址，设置圆形头像
     */
    @SuppressLint("StaticFieldLeak")
    private void setHeadImageAfterUpload() {
        if (photoPath != null && photoPath.equals("")) {
            return;
        }
        if (photoPath != null) {
            Bitmap bitmap = Bimp.Compression(photoPath, 240, 240);
            photoPath = saveBitmap(bitmap);
        }
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                String url = GcUrl.HOST + "/api/group/uploadGroupImg/" + groupID;
                String response = com.etogc.groupchat.mine.UploadImageUtil.uploadFile(new File(String.valueOf(params[0])), url);
                return response;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                Log.e("MineFragment", "开始上传");
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                String s = o.toString();
                UpdatePhotoBean updatePhotoBean = new Gson().fromJson(s, UpdatePhotoBean.class);
                if (updatePhotoBean.getResultCode() == 200) {
                    String photo = ImageUtils.getImageUrl(updatePhotoBean.getData().getPhoto());
                    ImageUtils.setRadiuImage(MgrGroupActivity.this, photo, mIvGrouId);
                }
            }
        }.execute(photoPath);
    }

    /**
     * 请求群组信息
     */
    private void requestInfo() {
        GroupHttpBiz2.getGroupInfo(this, groupID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(MgrGroupActivity.this);
                boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response, true);
                if (isSuccess) {
                    Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                    mGroupInfo = (Map<String, Object>) map.get("groupinfo");
                    String groupName = String.valueOf(mGroupInfo.get("group_name"));
                    String headPath = String.valueOf(mGroupInfo.get("photo"));
                    String groupId = String.valueOf(mGroupInfo.get("id"));
                    String remark = String.valueOf(mGroupInfo.get("remark"));
                    mTvGrouName.setText(groupName);
                    mTvGrouId.setText(groupId);
                    mGroupName.setText(groupName);
                    mEtIntro.setText(remark);
                    ImageUtils.setRadiuImage(MgrGroupActivity.this, ImageUtils.getImageUrl(headPath), mIvGrouId);
                }
            }
        });
    }

    /**
     * 请求成员信息
     */
    private void requestMemberNum() {
        GroupHttpBiz2.getMemberList(this, groupID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(MgrGroupActivity.this);
                boolean isSuccess = ReqErrorHandler.getInstance().isSuccess(response, true);
                if (isSuccess) {
                    Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                    memberList = (List<HashMap<String, String>>) map.get("list");
                    if (memberList != null && memberList.size() > 0) {
                        hasMember = true;
                        tvMemberNum.setText(memberList.size() + "名成员");
                        List<HashMap<String, String>> fourMemberList = new ArrayList<>();
                        for (int i = 0; i < 4; i++) {
                            if (i < (memberList.size() - 1)) {
                                fourMemberList.add(memberList.get(i));
                            }
                        }
                        memberAdapter.setData(fourMemberList);
                        memberAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    /**
     * 更新简介
     *
     * @param info
     */
    private void updateGroupInfo(String info) {
        LoadDialog.show(this);
        HashMap<String, Object> map = new HashMap<>();
        map.put("group_id", groupID);
        map.put("remark", info);
        map.put("type", "0");//0=app,1=pc
        VolleyHttpUtil.getInstance().postWithCallback(GcUrl.UPDATE_GROUP_INFO, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                LoadDialog.dismiss(MgrGroupActivity.this);
                boolean isOk = ReqErrorHandler.getInstance().isSuccess(response, true);
                Log.e("Biz", response.toString());
                if (isOk) {
                    YcToastHelper.getInstance()._toast("修改资料成功");
                    requestInfo();
                }
            }
        });
    }

    private void jumpMgrMember() {
        IntentHelper.jump(this, MgrMemberActivity.class, "groupID", groupID);
    }

    /**
     * 成员适配器
     */
    public class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.MyViewHolder> {

        private List<HashMap<String, String>> mList = new ArrayList<>();

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.group_mgr_item, null);
            return new MyViewHolder(view);
        }

        public void setData(List<HashMap<String, String>> list) {
            this.mList = list;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            try {
                HashMap<String, String> map = mList.get(position);
                String photo = ImageUtils.getImageUrl(map.get("photo"));
                ImageUtils.setCircleImage(MgrGroupActivity.this, photo, holder.mImage);
            } catch (Exception e) {
                e.printStackTrace();
                holder.mImage.setImageResource(R.mipmap.ic_launcher);
            }
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            public ImageView mImage;

            public MyViewHolder(View itemView) {
                super(itemView);
                mImage = itemView.findViewById(R.id.ivImage);
            }
        }
    }
}
